#include "link_stack.h"

int create_stack(stack_t **p){
    if(NULL == p){
        printf("入参为NULL 请检查\n");
        return -1;
    }
    *p = (stack_t *)malloc(sizeof(stack_t));
    if(NULL == *p){
        printf("内存分配失败\n");
        return -1;
    }
    (*p)->top = NULL;
    (*p)->count = 0;
    return 0;
}

int clean_stack(stack_t *my_stack){
    if(NULL == my_stack){
        printf("入参为NULL 请检查\n");
        return -1;
    }
    //循环头删 释放所有数据节点
    node_t *pdel = NULL;
    while(NULL != my_stack->top){
        pdel = my_stack->top;
        my_stack->top = pdel->next;
        free(pdel);
    }
    pdel = NULL;
    my_stack->count = 0;
    return 0;
}

int destroy_stack(stack_t **my_stack){
    if(NULL == my_stack || NULL == *my_stack){
        printf("入参为NULL 请检查\n");
        return -1;
    }
    // 先清空再销毁
    clean_stack(*my_stack);
    free(*my_stack);
    *my_stack = NULL;
    return 0;
}

int push_stack(stack_t *my_stack, int num){
    if(NULL == my_stack){
        printf("入参为NULL 请检查\n");
        return -1;
    }
    // 创建新节点
    node_t *pnew = (node_t *)malloc(sizeof(node_t));
    if(NULL == pnew){
        printf("内存分配失败\n");
        return -1;
    }
    pnew->data = num;
    // 头插到链表中
    pnew->next = my_stack->top;
    my_stack->top = pnew;
    my_stack->count++;
    return 0;
}

int pop_stack(stack_t *my_stack, int *buff){
    if(NULL == my_stack || NULL == buff){
        printf("入参为NULL 请检查\n");
        return -1;
    }
    if(is_empty(my_stack)){
        printf("栈空 出栈失败\n");
        return -1;
    }
    *buff = my_stack->top->data;
    node_t *pdel = my_stack->top;
    my_stack->top = pdel->next;
    free(pdel);
    pdel = NULL;
    my_stack->count--;
    return 0;
}

// 返回1 空了  返回0 没空
int is_empty(stack_t *my_stack){
    if(NULL == my_stack){
        printf("入参为NULL 请检查\n");
        return -1;
    }
    return NULL == my_stack->top ? 1 : 0;
}

int print_stack(stack_t *my_stack){
    if(NULL == my_stack){
        printf("入参为NULL 请检查\n");
        return -1;
    }
    node_t *ptemp = my_stack->top;
    while(NULL != ptemp){
        printf("%d ", ptemp->data);
        ptemp = ptemp->next;
    }
    printf("\n");
    return 0;
}

